package com.frinder.official.akka.actors;

import akka.actor.ActorRef;
import akka.actor.Inbox;
import akka.actor.PoisonPill;
import akka.actor.Terminated;
import com.frinder.official.spring.Actors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;

/**
 * Created by frinder on 2017/9/12.
 * <p>
 * 收件箱
 */
@Component
public class InBox implements CommandLineRunner {

    final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Actors actors;

    @Override
    public void run(String... strings) throws Exception {
        final Inbox inbox = actors.getInbox();
        final ActorRef myActor = actors.getActorRef("myActor");
        // 测试一
        inbox.send(myActor, "world");
        try {
            Object respond = inbox.receive(Duration.create(1, TimeUnit.SECONDS));
            assert respond.equals("world") : String.format("Expect {%s}, Actual {%s}", "world", respond);
            logger.info("respond : {}", respond);
        } catch (java.util.concurrent.TimeoutException e) {
            // timeout
            logger.error(e.getMessage(), e);
        }
        // 测试二
        inbox.watch(myActor);
        myActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
        try {
            Object respond = inbox.receive(Duration.create(1, TimeUnit.SECONDS));
            assert respond instanceof Terminated;
            logger.info("respond : {}", respond);
        } catch (java.util.concurrent.TimeoutException e) {
            // timeout
            logger.error(e.getMessage(), e);
        }
    }
}
